<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>使用ajax构造post请求</title>
</head>
<body>
    <!-- <form action="getParameter" method="post">
        <input type="text" name="userId">
        <input type="text" name="classId">
        <input type="submit" value="提交">
    </form> -->

    <input type="text" id="userId">
    <input type="text" id="classId">
    <input type="button" value="提交" id="submit">

    <script src="jQuery.js"></script>
    <script>
        let userIdInput = document.querySelector("#userId");
        let classIdInput = document.querySelector("#classId");
        let button = document.querySelector("#submit");
        button.onclick = function() {
            $.ajax({
                type: 'post',
                url: 'postJson',
                // 手动将contentType的内容设为json
                contentType: "application/json",
                // 对于post请求，ajax就允许使用data属性来构造请求的body部分
                data: JSON.stringify({
                    // 此处构造的是js对象，我们需要通过JSON.stringify将对象转成字符串
                    userId: userIdInput.value,
                    classId: classIdInput.value
                }),
                success: function(body) {
                    console.log(body);
                },
                error: function(body) {
                    console.log("获取响应失败");
                }
            });
        }
    </script>


    <!-- <script>
        $.ajax ({
            type: 'post',
            // 注意，这里的路径前面不能加斜杠，不加斜杠是相对路径，如果加了斜杠，就成了绝对路径
            url: 'method',
            success: function(body) {
                console.log(body);
            }
        });
    </script> -->
</body>
</html>